package com.garden.rocketmq.learn.samples.config.producer;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 顺序生产者配置类 用于配置顺序生产者Bean
 * Created by Garden on 2021-01-20 14:13
 */
@Configuration
public class OrderProducerConfig {

    public static final Logger LOGGER = LoggerFactory.getLogger(OrderProducerConfig.class);

    @Value("${rocketmq.producer.order.groupName}")
    private String groupName;
    @Value("${rocketmq.producer.order.namesrvAdrr}")
    private String namesrvAddr;

    @Bean(name = "orderProducer")
    @ConditionalOnMissingBean
    public DefaultMQProducer orderProducer() throws RuntimeException {

        //构建顺序生产者对象，设置属性
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer(this.groupName);
        //设置NameServer的地址，Producer启动后通过NameServer获取目标Topic的路由信息
        defaultMQProducer.setNamesrvAddr(this.namesrvAddr);

        //启动实例
        try {
            defaultMQProducer.start();
            LOGGER.info("order producer start success... groupName={},namesrvAdrr={}",this.groupName,this.namesrvAddr);
        } catch (MQClientException e) {
            LOGGER.error("order producer start failed... errorMsg={}",e.getErrorMessage());
            throw new RuntimeException(e);
        }

        //返回Bean
        return defaultMQProducer;
    }

}
